package homework.dao.impl;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.DatabaseMetaData;

import homework.dao.StudentDao;
import homework.entity.StudentEntity;
import homework.utils.DBUtil;

public class StudentDaoImpl implements StudentDao {
	private Connection conn;
	private static PreparedStatement stmt;

	private ResultSet rs;
	
	

	@Override
	public void add(StudentEntity entity) throws Exception {
		
		String sql="INSERT INTO hw_student(STUDENT_NAME,PHONE,CLASS_ID) VALUES(?,?,?)";
		Connection conn = DBUtil.getConn();
		stmt = conn.prepareStatement(sql);
		stmt.setString(1,entity.getStudentName());
		stmt.setString(2,entity.getPhone());
		stmt.setInt(3,entity.getClassId());
		
		int i = stmt.executeUpdate();
		//处理结果
		if(i>0){
			System.out.println("add成功");
		}
		//关闭
		DBUtil.release(rs, stmt);
		
		
	}

	@Override
	public void del(int id) throws Exception {
		String sql="DELETE FROM hw_student WHERE ID=?";
		conn= DBUtil.getConn();
		stmt= conn.prepareStatement(sql);
		
		stmt.setInt(1, id);
		int i= stmt.executeUpdate();
		//处理结果
		if(i>0){
			System.out.println("del成功");
		}
		//关闭
		DBUtil.release(rs, stmt);
		
	}

	@Override
	public boolean update(int id) throws Exception {
		String sql="UPDATE  hw_student SET STUDENT_NAME=?,PHONE=?,CLASS_ID=? WHERE ID=?;";
		Connection conn = DBUtil.getConn();
		stmt = conn.prepareStatement(sql);
		stmt.setObject(1, "狗剩");
		stmt.setObject(2, "1233");
		stmt.setObject(3, 2);
		stmt.setObject(4, id);
		int i = stmt.executeUpdate();
		
		//处理结果
		if(i>0){
			System.out.println("update成功");
		}
		//关闭
		DBUtil.release(rs, stmt);

		return false;
	}

	@Override
	public StudentEntity query(int id) throws Exception {
		StudentEntity entity=new StudentEntity();
		String sql="SELECT  STUDENT_NAME,PHONE,CLASS_ID FROM  hw_student WHERE ID=?";
		Connection conn = DBUtil.getConn();
		stmt = conn.prepareStatement(sql);
		stmt.setInt(1, id);
		
		rs=stmt.executeQuery();
		while(rs.next()){
			
			entity.setStudentName(rs.getString("STUDENT_NAME"));
			entity.setPhone(rs.getString("PHONE"));
			
		}
		//关闭
		DBUtil.release(rs, stmt);
		return entity;
	}

	@Override
	public List<StudentEntity> queryConditions(StudentEntity entity) throws Exception {
		List<StudentEntity> arrayList=new ArrayList<StudentEntity>();
		String sql="SELECT  STUDENT_NAME,PHONE,CLASS_ID FROM  hw_student WHERE STUDENT_NAME=?";
		stmt = DBUtil.getstmt(sql);
		stmt.setString(1, entity.getStudentName());
		rs = stmt.executeQuery();
		while(rs.next()){
			StudentEntity et=new StudentEntity();
			et.setStudentName(rs.getString("STUDENT_NAME"));
			et.setPhone(rs.getString("PHONE"));
			et.setClassId(rs.getInt("CLASS_ID"));
			arrayList.add(et);
		}
		
		DBUtil.release(rs, stmt);
		return arrayList;
	}

	
	//反射方法
	@Override
	public List<StudentEntity> queryName(String name) throws Exception {
		//建立连接
		
		List<StudentEntity> stuArray=new ArrayList<StudentEntity>();
		String sql="SELECT ID,STUDENT_NAME,PHONE,CLASS_ID FROM  hw_student WHERE STUDENT_NAME=?;";
		stmt = DBUtil.getstmt(sql);
		stmt.setString(1,name);
		ResultSet rs = stmt.executeQuery();
		ResultSetMetaData metaData = rs.getMetaData();
		StudentEntity entity=new StudentEntity();
		
//		得到当前对象的方法
		//----a.获取java对象的所有自定义方法
				Method[] methods = entity.getClass().getDeclaredMethods();
				
				while(rs.next()){
					int index = 1;
					while(index <= metaData.getColumnCount()){
//						System.out.print(metaData.getColumnName(index)+":"+rs.getString(index++)+"\t");
						
						//请注意 methods跟 数据库所有字段  是多对多的关系
						for(Method method:methods){
							String methodName = method.getName();
							//---b.确定哪个set方法，设置哪个属性（在所有set方法中找到对应属性的set方法）
							if(methodName.equalsIgnoreCase("set"+removeBottom(metaData.getColumnName(index)))){
								//"set"+removeBottom(..)是固定的，当匹配了这个字段后，跳到下一个字段（index++）
								
//								Class<?>[]pp = method.getParameterTypes();
								Class<?> forName = Class.forName(method.getParameterTypes()[0].getName());
								
								//---c.判断根据》对象属性的类型《，执行set方法（注意 参数类型）
								if(Integer.class == forName){					//只做了两个判断，做多个类型的判断可以使用switch
									method.invoke(entity, Integer.parseInt(rs.getString(index++)));
								}else{
									method.invoke(entity, rs.getString(index++));	//调用 set 方法将传入的value值保存属性中
								}
								break;
							}
						}
					}
					stuArray.add(entity);
				}
				//5.关闭资源
				return stuArray;
			}
			
		//去掉下划线
		public static String removeBottom(String name){
			String[] strArray = name.split("_");
			String newName = "";
			for(String str:strArray){
//					System.out.println(str+" ");
				newName += str;
			}
			return newName;
		}

		public boolean updateName(StudentEntity entity,String name) throws Exception {
			String sql="UPDATE  hw_student SET STUDENT_NAME=?,PHONE=?,CLASS_ID=? WHERE STUDENT_NAME=?;";
			Connection conn = DBUtil.getConn();
			stmt = conn.prepareStatement(sql);
			stmt.setString(4,name);
			
			Method[] methods = entity.getClass().getDeclaredMethods();
			int counter=1;
			for(int index=0;index<methods.length;index++){
				String methodName = methods[index].getName();
				String reg="get.*";
				if(!methodName.equalsIgnoreCase("getSTUDENTNAME") && methodName.matches(reg)){
					stmt.setString(counter++, (String) methods[index].invoke(entity));
				}
			}
			int i = stmt.executeUpdate();
			
			if(i!=0){
				return true;
			}else{
				return false;
			}
		}
}
